<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable @keyup.enter="handleQuery"
          style="width: 200px" />
      </el-form-item>
      <!-- <el-form-item label="创建人" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建人" clearable @keyup.enter="handleQuery"
          style="width: 250px" />
      </el-form-item> -->
      <el-form-item label="模版尺寸" prop="printerSize">
        <el-select v-model="queryParams.printerSize" @change="handleQuery" clearable>
            <el-option v-for="dict in printerSizeList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="模版类型" prop="templateType">
        <el-select v-model="queryParams.templateType" @change="handleQuery" clearable>
            <el-option v-for="dict in content_label_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="绑定总部" prop="storeId" v-if="roles.includes('admin')">
        <el-select v-model="queryParams.storeId" @change="handleQuery" clearable>
            <el-option v-for="dict in headquartersList" :key="dict.storeId" :label="dict.storeName" :value="dict.storeId" />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="small" icon="Plus" @click="handleAdd" v-hasPermi="['manage:template:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" size="small" icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:template:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" size="small" icon="Download" @click="handleExport"
          v-hasPermi="['manage:template:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="templateList" @selection-change="handleSelectionChange" @row-click="(row)=>(console.log(row))">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="模板尺寸" align="center" prop="printerSize" />
      <el-table-column label="状态" align="center" prop="isStatus">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.isStatus" />
        </template>
      </el-table-column>
      <el-table-column label="模版类型" align="center" prop="templateType">
        <template #default="scope">
          <dict-tag type="default" :options="content_label_type" :value="scope.row.templateType" />
        </template>
      </el-table-column>
      <el-table-column label="绑定总部" align="center" prop="headquartersNames" v-if="roles.includes('admin')" />
      <el-table-column label="模板样式" align="center" prop="templateContent">
        <template #default="scope">
          <el-tooltip
            :content="generateHtml(JSON.parse(scope.row.templateContent))"
            raw-content placement="right">
            <span class="text-blue cursor-pointer">显示模版</span>
          </el-tooltip>
        </template>
      </el-table-column>
      
      <!-- <el-table-column label="创建人" align="center" prop="createBy" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="200" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" v-hasPermi="['manage:template:edit']">
        <template #default="scope">
            <el-link icon="Edit" class="table_link_btn" type="primary"  :underline="false" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:template:edit']"><span class="table_link_text">修改</span></el-link>
          <el-link icon="Delete" class="table_link_btn" type="danger"  :underline="false" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:template:remove']"><span class="table_link_text">删除</span></el-link>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改打印模板对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="templateRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="绑定总部" prop="storeId">
          <el-select v-model="form.storeId" multiple placeholder="请选择总部" class="w-full">
              <el-option v-for="ele in headquartersList" :value="ele.storeId" :key="ele.storeId" :label="ele.storeName" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板类型" prop="templateType">
          <el-select v-model="form.templateType" class="w-full">
              <el-option v-for="size in content_label_type" :value="size.value" :key="size.value" :label="size.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="模版内容" prop="templateContent">
          <!-- <el-input v-model="form.templateContent" placeholder="请输入模板名称" clearable /> -->
          <el-input
            v-model="form.templateContent"
            autosize
            type="textarea"
            placeholder="请输入模板内容"
          />
          <!-- <el-area -->
        </el-form-item>
        <el-form-item label="模版尺寸" prop="printerSize">
          <el-select v-model="form.printerSize">
              <el-option v-for="size in printerSizeList" :value="size.value" :key="size.value" :label="size.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="模版状态" prop="isStatus">
          <el-radio-group v-model="form.isStatus">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        
        
        
        <!-- <PrinterModel :printerSize="form.printerSize" v-model="form.templateContent" />  -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Template" lang="ts">
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from '@/api/manage/template';
import { getCurrentInstance, ref, watch } from 'vue';
import PrinterModel from './component/printerModel.vue';
import { easyListStore, listStore } from '@/api/system/store';
import { generateHtml } from '@/utils/generateHtml';
import useUserStore from '@/store/modules/user';
const { roles } = useUserStore();
const { proxy } = getCurrentInstance() as any;
const templateList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const names = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const queryRef = ref();
const headquartersList = ref<any[]>([]); // 总部列表
const printerSizeList = [{ label: '40 * 30', value: '40 * 30' }, { label: '50 * 30', value: '50 * 30' }, { label: '60 * 40', value: '60 * 40' }];
const form: any = ref({});
const { sys_normal_disable } = proxy.useDict('sys_normal_disable');
const { content_label_type } = proxy.useDict('content_label_type');
// 监控是否选择了通用，
watch(()=>form.value.storeId,(newVal)=>{
	if(!newVal) return;
	if(newVal.includes('1')){
		form.value.storeId = ['1'];
	}
});

const queryParams = ref({
	pageNum: 1,
	pageSize: 10,
	templateName: null, 
	printerSize:'',
	templateType: '',
	storeId:''
});
const rules = ref({
	templateName: [{ required: true,message: '模版名称不能为空',trigger: 'blur' }],
	templateContent: [{ required: true,message: '模版内容不能为空',trigger: 'blur' }],
	// createBy: [{ required: true,message: '创建人不能为空',trigger: 'blur' }],
	printerSize: [{ required: true,message: '模版尺寸不能为空',trigger: 'blur' }],
	storeId: [{ required: true,message: '总部绑定不能为空',trigger: 'blur' }],
	templateType: [{ required: true,message: '模板类型不能为空',trigger: 'blur' }],
});

/** 查询打印模板列表 */
function getList() {
	loading.value = true;
	listTemplate(queryParams.value).then((response: any) => {
		console.log(response, '查询打印模板列表');
		templateList.value = response.data.list;
		total.value = response.data.total;
		loading.value = false;
	});
}
// 取消按钮
function cancel() {
	open.value = false;
	reset();
}

// 表单重置
function reset() {
	form.value = {
		id :null,
		templateName: '', 
		templateContent: '', 
		isStatus: '0',
		printerSize:'50 * 30',
		templateType:'1',
		storeId:[]
	};
	proxy.resetForm('templateRef');
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1;
	getList();
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm(queryRef);
	handleQuery();
}
/** 查询门店下拉树结构 */
const getStoreList = async () => {
	const storeRes = await easyListStore({});
	headquartersList.value = storeRes.data.filter((ele:any)=>ele.storeLb === '1');
	// headquartersList.value.unshift({storeId:'1',storeName:'通用'});
	console.log(headquartersList.value,'门店下拉结构');
	// deptOptions.value = proxy.handleTree(storeRes.data, 'storeId');
};

// 多选框选中数据
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
	names.value = selection.map((item: any) => item.templateName);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
	reset();
	open.value = true;
	title.value = '添加打印模板';
}

/** 修改按钮操作 */
function handleUpdate(row: any) {
	console.log(row,'000');
	reset();
	form.value = Object.assign({},row);
	open.value = true;
	title.value = '修改打印模板';
	// const id = row.id || ids.value;
	// getTemplate(id).then(response => {
		
	// });
}

/** 提交按钮 */
function submitForm() {
	proxy.$refs['templateRef'].validate((valid: any) => {
		if (valid) {
			if (form.value.id !== null) {
				updateTemplate(form.value).then(response => {
					proxy.$modal.msgSuccess('修改成功');
					open.value = false;
					getList();
				});
			} else {
				addTemplate(form.value).then(response => {
					proxy.$modal.msgSuccess('新增成功');
					open.value = false;
					getList();
				});
			}
		}
	});
}

/** 删除按钮操作 */
function handleDelete(row?: any) {
	const namesValue = row.templateName || names.value;
	const delIds = row.id || ids.value;
	proxy.$modal.confirm('是否确认删除打印模板编号为"' + namesValue + '"的数据项？').then(function () {
		return delTemplate(delIds);
	}).then(() => {
		getList();
		proxy.$modal.msgSuccess('删除成功');
	}).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
	proxy.download('manage/template/exportByStream', {
		...queryParams.value
	}, `template_${new Date().getTime()}.xlsx`);
}
getStoreList();
getList();
</script>